package com.njcky.utils.db;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 数据库连接池配置类（由Spring管理，正确读取配置文件）
 */
@Configuration // 标记为配置类，让Spring扫描并管理
public class DBPool2Util {

    @Value("${pgLink.url}")
    private String pgUrl;

    @Value("${pgLink.username}")
    private String pgUserName;

    @Value("${pgLink.password}")
    private String pgPassword;

    @Value("${pgLink.hikari.maximum-pool-size}")
    private int maximumPoolSize;

    @Value("${pgLink.hikari.minimum-idle}")
    private int minimumIdle;

    @Value("${pgLink.hikari.idle-timeout}")
    private long idleTimeout;

    @Value("${pgLink.hikari.max-lifetime}")
    private long maxLifetime;

    /**
     * 定义DataSource Bean，由Spring管理连接池生命周期
     * 连接池参数从配置文件读取，实现灵活配置
     */
    @Bean // 声明为Bean，让Spring管理
    public DataSource connectivityPublic() {
        HikariConfig config = new HikariConfig();
        // 数据库连接基本配置
        config.setJdbcUrl(pgUrl);
        config.setUsername(pgUserName);
        config.setPassword(pgPassword);
        config.setMaximumPoolSize(maximumPoolSize);
        config.setMinimumIdle(minimumIdle);
        config.setIdleTimeout(idleTimeout);
        config.setMaxLifetime(maxLifetime);
        HikariDataSource dataSource = new HikariDataSource(config);
        Runtime.getRuntime().addShutdownHook(new Thread(dataSource::close));
        return dataSource;
    }
}
